#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from util import mysql_util

def storage_mysql(universities):
    connection, cursor = None, None;
    try:
        # 执行插入操作，并提交事务
        connection, cursor = mysql_util.get_connection_cursor()
        for university in universities:
            university_id = university["id"]
            query_sql = "select * from university where id = '%s'" % (university_id,)
            insert_sql = "insert into university(id, school_name, type, level, nature, belong, " \
                         "central, department, doublehigh, f211, f985, is_recruitment, dual_class, " \
                         "address, province_name, single_province, city_name, county_name, view_total_number) " \
                         "values ('%s', '%s', '%s', '%s', '%s', '%s', %s, %s, %s, %s, %s, %s, " \
                         "'%s', '%s', '%s', '%s', '%s', '%s', %s)"%(university.get('id', None), \
                         university.get('school_name', None), university.get('type', None),  \
                         university.get('level', None), university.get('nature', None),  \
                         university.get('belong', None), university.get('central', None),  \
                         university.get('department', None), university.get('doublehigh', None),  \
                         university.get('f211', None), university.get('f985', None),  \
                         university.get('is_recruitment', None), university.get('dual_class', None),  \
                         university.get('address', None), university.get('province_name', None),  \
                         university.get('single_province', None), university.get('city_name', None),  \
                         university.get('county_name', None), university.get('view_total_number', None))
            insert_sql = insert_sql.replace("None", "null")

            result = mysql_util.execute_query(query_sql, cursor)
            if len(result):
                continue
            mysql_util.execute_insert_update_delete(insert_sql, cursor)

        mysql_util.commit_(connection)
    except Exception as e:
        print(e)
        # 回滚数据
        mysql_util.rollback_(connection)
    finally:
        # 关闭连接、游标
        mysql_util.close_(connection, cursor)
